package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/TeacherChangePasswordServlet")
public class TeacherChangePasswordServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); // 添加字符编码设置
        HttpSession session = request.getSession(false); // 不创建新会话
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> jsonResponse = new HashMap<>();

        // 会话验证
        if (session == null || session.getAttribute("teacher_id") == null) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "会话已过期，请重新登录");
            out.print(mapToJson(jsonResponse));
            return;
        }

        Integer teacherId = (Integer) session.getAttribute("teacher_id");
        String currentPass = request.getParameter("current-password") != null ?
                request.getParameter("current-password") : "";
        String newPass = request.getParameter("new-password") != null ?
                request.getParameter("new-password") : "";
        String confirmPass = request.getParameter("confirm-password") != null ?
                request.getParameter("confirm-password") : "";

        // 验证新密码一致性
        if (!newPass.equals(confirmPass)) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "两次输入的新密码不一致");
            out.print(mapToJson(jsonResponse));
            return;
        }

        // 检查当前密码是否为空
        if (currentPass == null || currentPass.trim().isEmpty()) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "请输入当前密码");
            out.print(mapToJson(jsonResponse));
            return;
        }

        // 调试输出
        System.out.println("修改密码请求 - teacherId: " + teacherId);
        System.out.println("当前密码: [" + currentPass + "]");
        System.out.println("新密码: [" + newPass + "]");

        Connectmysql conn = null;
        try {
            conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver"
            );

            if (conn.open()) {
                // 验证当前密码
                String checkSql = "SELECT password FROM teacher WHERE teacher_id = ?";
                ResultSet rs = conn.executeSql(checkSql, new Object[]{teacherId});

                if (rs.next()) {
                    String dbPassword = rs.getString("password");

                    // 调试输出
                    System.out.println("数据库密码: [" + dbPassword + "]");
                    System.out.println("密码匹配结果: " + currentPass.equals(dbPassword));

                    if (currentPass.equals(dbPassword)) {
                        // 更新密码（明文存储）
                        String updateSql = "UPDATE teacher SET password = ? WHERE teacher_id = ?";
                        int result = conn.executeSqlUpdate(updateSql, new Object[]{newPass, teacherId});

                        if (result > 0) {
                            jsonResponse.put("success", true);
                            jsonResponse.put("message", "密码修改成功，请重新登录");
                            session.invalidate(); // 使会话失效
                        } else {
                            jsonResponse.put("success", false);
                            jsonResponse.put("message", "密码更新失败，数据库无变化");
                        }
                    } else {
                        jsonResponse.put("success", false);
                        jsonResponse.put("message", "当前密码不正确");
                    }
                } else {
                    jsonResponse.put("success", false);
                    jsonResponse.put("message", "未找到教师信息");
                }
            } else {
                jsonResponse.put("success", false);
                jsonResponse.put("message", "数据库连接失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResponse.put("success", false);
            jsonResponse.put("message", "数据库错误: " + e.getMessage());
        } finally {
            if (conn != null) {
                conn.close();
            }
            // 调试输出响应
            System.out.println("修改密码响应: " + mapToJson(jsonResponse));
            out.print(mapToJson(jsonResponse));
            out.flush();
        }
    }

    // 将 Map 转换为 JSON 字符串
    private String mapToJson(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean first = true;

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) {
                json.append(",");
            }
            first = false;

            json.append("\"")
                    .append(entry.getKey())
                    .append("\":");

            Object value = entry.getValue();
            if (value instanceof String) {
                json.append("\"")
                        .append(value)
                        .append("\"");
            } else if (value instanceof Boolean) {
                json.append(value);
            } else {
                json.append("\"")
                        .append(value)
                        .append("\"");
            }
        }

        json.append("}");
        return json.toString();
    }
}